import { useEffect, useState } from 'react';

import { useRefresh } from '@flowgram.ai/free-layout-editor';
import { useClientContext } from '@flowgram.ai/free-layout-editor';

import { cn } from '@/lib/utils';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

import { ToolContainer, ToolSection } from './styles';
import { McpSetting } from './mcp-settings';
import { LlmSetting } from './llm-settings';

export const SettingTools = () => {
  const { playground } = useClientContext();
  const [open, setOpen] = useState(false);
  const [isLlmSettingOpen, setIsLlmSettingOpen] = useState(false);
  const [isMcpSettingOpen, setIsMcpSettingOpen] = useState(false);
  const refresh = useRefresh();

  useEffect(() => {
    const disposable = playground.config.onReadonlyOrDisabledChange(() => refresh());
    return () => disposable.dispose();
  }, [playground]);

  return (
    <>
      <ToolContainer className="demo-free-layout-tools">
        <ToolSection>
          <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>
            <DropdownMenuTrigger asChild>
              <button className={cn('h-8 w-20 rounded-md md:text-xs border')}>系统设置</button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className={cn('w-56')}>
              <DropdownMenuLabel>系统设置</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onSelect={() => setIsLlmSettingOpen(true)}>
                大模型设置
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => setIsMcpSettingOpen(true)}>
                MCP设置
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </ToolSection>
      </ToolContainer>
      <LlmSetting open={isLlmSettingOpen} onOpenChange={setIsLlmSettingOpen} />
      <McpSetting open={isMcpSettingOpen} onOpenChange={setIsMcpSettingOpen} />
    </>
  );
};
